// logs.js
const util = require('../../utils/util.js')
let conversation_id = '';
import "../../utils/env";
import env from "../../utils/env";

Page({
    data: {
        logs: [],
        message: '',
        disabled: false,
        plain: false,
        downloaddisabled: false,
        downloadloading: false,
        loading: false,
        downloadUrl: '',
        playlistid: '',
        result: '',
        q: '',
        dialogShow: false,
        maxClickCount: 3, //定义允许最大的点击次数，超过次数需要有分享或者其他逻辑处理
        price: '请选择套餐',
        prodCode: '',
        supplier: '',
        indexstatus: -1,//默认显示
        hideModal: true, //模态框的状态  true-隐藏  false-显示
        animationData: {},//
        areaList: [
            '0.03元\n次', '0.05元\n两次', '0.1元\n五次']
    },
    submitForm: function (e) {
        console.log("maxClickCount=====", this.data.maxClickCount)
        let data = e.detail.value
        if (!data.q || "" == data.q) {
            this.setData({
                message: '请输入您的项目经历',
            })
            return;
        }

        this.setData({
            message: '正在努力加载中...',
            disabled: true,
            loading: true
        })
        console.log("datamodel==", data)
        let req;
        if (conversation_id == null || conversation_id == '') {
            req = {
                prompt: e.detail.value.q,
            }
        } else {
            req = {
                prompt: e.detail.value.q,
                conversation_id: conversation_id
            }
        }
        console.log("reqdata==", req)
        const that = this;
        wx.request({
            url: env.gpt_api_host + '/ask/',
            method: 'post',
            header: {
                "content-type": "application/json"
            },
            data: req,
            success(rsp) {
                if (rsp.data && rsp.data.data && rsp.data.answer) {
                    console.log("ask result-----", rsp.data.answer)
                }
                that.setData({
                    result: rsp.data.answer,
                    disabled: false,
                    loading: false,
                    message: ''
                })
            },
            complete(d) {
                console.log(d);
                if (d.statusCode == 200) {
                    conversation_id = d.data.conversation_id;
                } else if (d.statusCode == 502 || d.statusCode == 500) {
                    that.setData({
                        result: "很抱歉我暂时不能回答您的问题，请您换个问题或者稍后再试",
                        disabled: false,
                        loading: false,
                        message: ''
                    })
                } else {
                    that.setData({
                        result: "很抱歉服务器出现" + d.statusCode + "错误，请联系管理员",
                        disabled: false,
                        loading: false,
                        message: ''
                    })
                }
            }
        })
        console.info("form.submited")
    },
    goPay() {
        if (this.data.price == '请选择套餐') {
            wx.showModal({
                title: '温馨提示',
                content: '请您选择一个套餐',
                showCancel: false
            })
            return;
        } else {
            var third_session = wx.getStorageSync('third_session');
            this.generateOrder(third_session);
        }
    },
    /**生成商户订单 */
    generateOrder: function (orderId) {
        var that = this;
        var priceTemp = this.data.price;
        if (priceTemp == 0) {
            priceTemp = 3;
        } else if (priceTemp == 1) {
            priceTemp = 5;
        } else {
            priceTemp = 10;
        }
        console.log(orderInfo);      //统一支付
      console.log(Authorization);   
        //统一支付
        wx.request({
            url: env.api_host + '/userAccount/info/miniGenerateOrder',//
            method: 'GET',
            header: {
              Authorization: Authorization,
            },
            data: {
                gPrice: priceTemp,
                gName: '咨询服务费',
                thirdSession: orderId
            },
            success: function (res) {
                var payInfo = res.data;
                console.log(payInfo);
                //发起支付
                var timeStamp = payInfo.timeStamp;
                var packages = payInfo.package;
                var paySign = payInfo.paySign;
                var nonceStr = payInfo.nonce_str;
                var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr, "priceTemp": priceTemp };
                that.pay(param);
            },
            complete: function (res) {
                console.log(res);
            }
        })
    },

    /* 支付  */
    pay: function (param) {
        var tempPrice = param.priceTemp;
        console.log("支付")
        wx.requestPayment({
            timeStamp: param.timeStamp,
            nonceStr: param.nonceStr,
            package: param.package,
            signType: param.signType,
            paySign: param.paySign,
            success: function (res) {
                console.log("requestPayment success");
                wx.navigateTo({
                    url: '/pages/interview/index?priceTemp=' + tempPrice,
                })
            },
            fail: function (res) {
                console.log("requestPayment fail");
                wx.showToast({
                    title: '支付失败',
                    icon: 'fail',
                    duration: 2000
                })
                // wx.navigateBack({
                //   delta: 1, // 回退前 delta(默认为1) 页面
                //   success: function (res) {
                //     console.log("success"); 
                //     wx.showToast({
                //       title: '支付失败',
                //       icon: 'fail',
                //       duration: 2000
                //     })
                //     wx.navigateBack({});
                //   },
                //   fail: function () {
                //       console.log("fail"); 
                //   },
                //   complete: function () {
                //     console.log("complete"); 
                // }
                // })
            },
            complete: function () {
                console.log("complete");
            }
        })
    },
    //取消支付
    channelSelect: function () {
        wx.showToast({
            title: "你取消了订单",
            icon: 'error'
        })
        wx.navigateBack({
            delta: 1, // 回退前 delta(默认为1) 页面
            success: function (res) {
                console.log("success");
                wx.showToast({
                    title: '支付成功',
                    icon: 'success',
                    duration: 2000
                })
            },
            fail: function () {
                console.log("fail");
            },
            complete: function () {
                console.log("complete");
            }
            // this.hidePay();
        })
    },
    download(e) {
        let pdfUrl = e.currentTarget.dataset.text
        console.log("download url", pdfUrl);
        const that = this;
        if (pdfUrl) {
            this.setData({
                message: '🎉抱歉，网络出现一些问题.',
                downloaddisabled: true,
                downloadloading: true
            })
        }

        wx.downloadFile({
            url: pdfUrl,
            success(res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode === 200) {
                    that.setData({
                        message: '🎉抱歉，网络出现一些问题',
                        disabled: false,
                        loading: false
                    })
                    let tmpFile = res.tempFilePath
                    console.log("tmp file path==", tmpFile)
                    wx.openDocument({
                        filePath: tmpFile,
                        fileType: 'pdf',
                        showMenu: true,
                        success(res) {
                            console.log("open document success", res)
                            that.setData({
                                message: '🎉',
                                downloaddisabled: false,
                                downloadloading: false
                            })
                        },
                        fail(res) {
                            console.log("open document fail", res)
                        }
                    })
                }
            }
        })
    },
    onLoad: function (option) {
        console.log(option.answer);
        this.setData({
            result: option.answer,
            disabled: false,
            loading: false,
            message: ''
        })
    },

    resetData() {
        console.log("reset clickCount to 0")
        let clickCountKey = 'clickCount'
        wx.setStorageSync(clickCountKey, 0)
        wx.setStorageSync('isShared', 1)
    },

    checkClickAuth(maxClickCount) {
        let isShared = wx.getStorageSync('isShared')
        console.log("isshared==", isShared)
        if (!isShared) {
            console.log("no shared..")
            let clickCountKey = 'clickCount'
            //clickCount
            let clickCount = wx.getStorageSync(clickCountKey)
            if (!clickCount || clickCount == 0) {
                clickCount = 1
            } else {
                clickCount = clickCount + 1
            }
            wx.setStorageSync(clickCountKey, clickCount)
            console.log("clickCount===", clickCount)
            if (clickCount > maxClickCount) {
                return false
            }
            return true
        }
        return true
    },
    tapDialogButton(e) {
        console.log("tap dailog info", e)
        this.setData({
            dialogShow: false,
        })

        if (e.detail.index == 1) {
            console.log("点击分享按钮")
            wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            })
        }
    },
    buttontap(e) {
        console.log(e.detail)
        console.log("点击分享按钮")
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    onShareAppMessage(options) {
        // return {
        //     title: 'chatGPT体验小助手',
        //     imageUrl: '',
        //     path: 'pages/chat/index'
        // }
    },
    onShareTimeline(options) {
        // return {
        //     title: 'chatGPT体验小助手',
        //     imageUrl: '',
        //     path: 'pages/chat/index'
        // }
    },
    StorageDetailsTap: function () {
        wx.navigateTo({
            url: '/pages/storageDetails/storageDetails',
        })
    },
    // 选择套餐
    getValueTap(e) {
        let dialogid = e.currentTarget.dataset.dialogid;
        console.log("dialogid==", dialogid);
        this.setData({
            price: dialogid,//this.data.areaList[dialogid] 赋值给输入框
            indexstatus: dialogid, //更新
        })
    },
    // 显示遮罩层
    showModal: function () {
        var that = this;
        that.setData({
            hideModal: false
        })
        var animation = wx.createAnimation({
            duration: 100,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
            timingFunction: 'ease',//动画的效果 默认值是linear
        })
        this.animation = animation
        setTimeout(function () {
            that.fadeIn();//调用显示动画
        }, 100)
    },

    // 隐藏遮罩层
    hideModal: function () {
        var that = this;
        var animation = wx.createAnimation({
            duration: 100,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
            timingFunction: 'ease',//动画的效果 默认值是linear
        })
        this.animation = animation
        that.fadeDown();//调用隐藏动画   
        setTimeout(function () {
            that.setData({
                hideModal: true
            })
        }, 100)//先执行下滑动画，再隐藏模块

    },

    //动画集
    fadeIn: function () {
        this.animation.translateY(0).step()
        this.setData({
            animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
        })
    },
    fadeDown: function () {
        this.animation.translateY(600).step()
        this.setData({
            animationData: this.animation.export(),
        })
    }
})
